from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import desc
from typing import List, Optional
from pydantic import BaseModel
from ..database import get_db
from ..models.contract import Contract
from ..models.employee import Employee

router = APIRouter()

class ContractBase(BaseModel):
    employee_id: int
    contract_number: str
    contract_type: str
    contract_party: str
    start_date: datetime
    end_date: datetime

class ContractCreate(ContractBase):
    pass

class ContractUpdate(ContractBase):
    pass

class ContractResponse(ContractBase):
    id: int
    is_expired: bool
    created_at: datetime
    updated_at: datetime

    class Config:
        orm_mode = True

def update_contract_expired_status(contract: Contract) -> None:
    """更新合同到期状态"""
    contract.is_expired = datetime.now() > contract.end_date
    contract.updated_at = datetime.now()

def update_all_contracts_status(db: Session) -> None:
    """更新所有合同的到期状态"""
    contracts = db.query(Contract).filter(Contract.is_expired == False).all()
    current_time = datetime.now()
    for contract in contracts:
        if current_time > contract.end_date:
            contract.is_expired = True
            contract.updated_at = current_time
    db.commit()

@router.get("/api/contracts")
def get_contracts(
    page: int = 1,
    page_size: int = 10,
    employee_name: Optional[str] = None,
    status: Optional[str] = None,
    db: Session = Depends(get_db)
):
    # 首先更新所有合同状态
    update_all_contracts_status(db)
    
    query = db.query(Contract).join(Employee)
    
    # 按员工姓名筛选
    if employee_name:
        query = query.filter(Employee.name.ilike(f"%{employee_name}%"))
    
    # 按合同状态筛选
    if status:
        is_expired = status == "expired"
        query = query.filter(Contract.is_expired == is_expired)
    
    # 按签订时间倒序排序
    query = query.order_by(desc(Contract.start_date))
    
    # 计算总数
    total = query.count()
    
    # 分页
    contracts = query.offset((page - 1) * page_size).limit(page_size).all()
    
    # 构造响应数据
    result = []
    for contract in contracts:
        contract_dict = contract.to_dict()
        contract_dict.update({
            "employee_name": contract.employee.name,
            "phone": contract.employee.phone
        })
        result.append(contract_dict)
    
    return {
        "items": result,
        "total": total
    }

@router.post("/api/contracts")
def create_contract(contract: ContractCreate, db: Session = Depends(get_db)):
    # 检查员工是否存在
    employee = db.query(Employee).filter(Employee.id == contract.employee_id).first()
    if not employee:
        raise HTTPException(status_code=404, detail="Employee not found")
    
    # 创建合同记录
    now = datetime.now()
    db_contract = Contract(
        employee_id=contract.employee_id,
        contract_number=contract.contract_number,
        contract_type=contract.contract_type,
        contract_party=contract.contract_party,
        start_date=contract.start_date,
        end_date=contract.end_date,
        created_at=now,
        updated_at=now
    )
    
    # 设置到期状态
    update_contract_expired_status(db_contract)
    
    db.add(db_contract)
    db.commit()
    db.refresh(db_contract)
    
    return db_contract.to_dict()

@router.put("/api/contracts/{contract_id}")
def update_contract(
    contract_id: int,
    contract: ContractUpdate,
    db: Session = Depends(get_db)
):
    # 检查合同是否存在
    db_contract = db.query(Contract).filter(Contract.id == contract_id).first()
    if not db_contract:
        raise HTTPException(status_code=404, detail="Contract not found")
    
    # 检查员工是否存在
    employee = db.query(Employee).filter(Employee.id == contract.employee_id).first()
    if not employee:
        raise HTTPException(status_code=404, detail="Employee not found")
    
    # 更新合同信息
    db_contract.employee_id = contract.employee_id
    db_contract.contract_number = contract.contract_number
    db_contract.contract_type = contract.contract_type
    db_contract.contract_party = contract.contract_party
    db_contract.start_date = contract.start_date
    db_contract.end_date = contract.end_date
    db_contract.updated_at = datetime.now()
    
    # 更新到期状态
    update_contract_expired_status(db_contract)
    
    db.commit()
    db.refresh(db_contract)
    
    return db_contract.to_dict()

@router.delete("/api/contracts/{contract_id}")
def delete_contract(contract_id: int, db: Session = Depends(get_db)):
    # 检查合同是否存在
    db_contract = db.query(Contract).filter(Contract.id == contract_id).first()
    if not db_contract:
        raise HTTPException(status_code=404, detail="Contract not found")
    
    # 删除合同
    db.delete(db_contract)
    db.commit()
    
    return {"message": "Contract deleted successfully"}

@router.get("/api/employees/search")
def search_employees(
    query: str,
    db: Session = Depends(get_db)
):
    employees = db.query(Employee).filter(
        Employee.name.ilike(f"%{query}%")
    ).all()
    
    return [{"id": emp.id, "name": emp.name} for emp in employees] 